const forge = require("node-forge");
const fs = require("fs");
const path = require("path");
const config = require("../config");

module.exports = function creteLocalCert() {
  const  localhostCertPath = path.resolve(config.sslCaDir,'./certs/localhost.pem')
  const  localhostKeyPath = path.resolve(config.sslCaDir,'./keys/localhost.key')

  const  caCertPemPath = path.resolve(config.sslCaDir,'./certs/ca.pem')
  const  caKeyPemPath = path.resolve(config.sslCaDir,'./keys/ca.private.key')
  if(fs.existsSync(localhostCertPath)&&fs.existsSync(localhostKeyPath)){
    console.log('localhost证书存在')
    return
  }
console.log('创建证书')
  // 加载CA证书和私钥
  const caCertPem = fs.readFileSync(caCertPemPath, "utf8");
  const caKeyPem = fs.readFileSync(caKeyPemPath, "utf8")
  const caCert = forge.pki.certificateFromPem(caCertPem);
  const caKey = forge.pki.privateKeyFromPem(caKeyPem)

  // 生成域名密钥对
  const keys = forge.pki.rsa.generateKeyPair(2048);
  const cert = forge.pki.createCertificate();

  cert.publicKey = keys.publicKey;
  cert.serialNumber = String(Date.now());
  cert.validity.notBefore = new Date();
  cert.validity.notAfter = new Date();
  cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1);

  // 设置证书的域名
  const attrs = [
    { name: "commonName", value: "localhost" },
    { name: "countryName", value: "US" },
    { shortName: "ST", value: "California" },
    { name: "localityName", value: "San Francisco" },
    { name: "organizationName", value: "Example Inc." },
    { shortName: "OU", value: "IT" },
  ];
  cert.setSubject(attrs);
  cert.setIssuer(caCert.subject.attributes);
  // 证书设置
  cert.setExtensions([
    {
      name: "basicConstraints",
      critical: true,
      cA: false,
    },
    {
      name: "keyUsage",
      keyCertSign: true,
      digitalSignature: true,
      nonRepudiation: true,
      keyEncipherment: true,
      dataEncipherment: true,
    },
    {
      name: "extKeyUsage",
      serverAuth: true,
      clientAuth: true,
      codeSigning: true,
      emailProtection: true,
      timeStamping: true,
    },
    {
      name: "nsCertType",
      client: true,
      server: true,
      email: true,
      objsign: true,
      sslCA: true,
      emailCA: true,
      objCA: true,
    },
    {
      name: "subjectAltName",
      // 这里填多个域名或者 ip
      altNames: [
        {
          type: 2, // DNS
          value: "localhost",
        },
        {
          type: 7, // ipv4
          ip: "127.0.0.1",
        },
        {
          type: 7, // ipv6
          ip: "[::1]",
        },
      ],
    },
    {
      name: "subjectKeyIdentifier",
    },
  ]);
  // 签名证书
  cert.sign(caKey, forge.md.sha256.create());

  // 将证书和私钥转换为PEM格式
  const pemCert = forge.pki.certificateToPem(cert);
  const pemKey = forge.pki.privateKeyToPem(keys.privateKey);

  // 保存证书和私钥
  fs.writeFileSync(localhostCertPath, pemCert);
  fs.writeFileSync(localhostKeyPath, pemKey);
};
// console.log('Domain certificate and key generated successfully');
